import { GetUserRoles } from "@/api/login";
import { defaultRouter, asyncRouter } from "@/router";

function haspeimission(roles, router) {
  if (router.meta && router.meta.role) {
    return roles.some(item => router.meta.role.indexOf(item) >= 0);
  }
}

const state = {
  addRouters: [],
  allRouters: defaultRouter
};
const getters = {
  addRouters: state => state.addRouters, // 匹配路由
  allRouters: state => state.allRouters // 所有的路由
};
const mutations = { // 必须 同步没有回调处理
  // 设置路由
  SET_ROUTER(state, value) {
    state.addRouters = value;
    state.allRouters = defaultRouter.concat(value);
  }
};
const actions = { // 可以有回调
  // 获取用户角色
  getRoles({ commit }) {
    return new Promise((resolve, reject) => {
      GetUserRoles().then(res => {
        let rolesData = res.data.data;
        resolve(res);
      }).catch(error => {
        reject(error);
      });
    });
  },
  // 创建动态路由
  creatRouter({ commit }, params) {
    return new Promise((resolve, reject) => {
      let role = params.data.data.role;

      let addRouters = [];
      // 超级管理员 处理
      if (role.includes("admin")) {
        addRouters = asyncRouter;
      } else { // 普通管理员
        addRouters = asyncRouter.filter(item => {
          if (haspeimission(role, item)) {
            // 优选判断
            if (item.children && item.children.length > 0) {
              item.children = item.children.filter(child => {
                if (haspeimission(role, child)) {
                  return child;
                }
              });
              return item;
            }
            return item;
          }
        });
        // 添加404
        addRouters.push(asyncRouter[asyncRouter.length - 1]);
      }
      // 更新路由
      commit("SET_ROUTER", addRouters);
      resolve();
    });
  }
};
export default {
  namespaced: true, // 解决命名空间问题
  state,
  getters,
  mutations,
  actions
};
